#include "visualobject.h"

VisualObject::VisualObject(QObject *parent, const QString &name)
    : AbstractGameObject(parent, name)
	, m_nHorizontalPattern(0)
	, m_nNumFrames(0)
	, m_fSpeed(1.0f)
	, m_bLoop(false)
{
}

bool VisualObject::isAnimation() const
{
    return m_frames.size() > 0;
}

GameObjectType VisualObject::type() const
{
	return GOT_VisualObject;
}

bool VisualObject::hasPhysics()
{
	return m_physicsObject != 0;
}

void VisualObject::setHorizontalPattern( int value )
{
	if(m_nHorizontalPattern != value)
	{
		m_nHorizontalPattern = value;
		emit dataChanged();
	}
}

int VisualObject::horizontalPattern() const
{
	return m_nHorizontalPattern;
}

void VisualObject::setNumFrames( int value )
{
	if(m_nNumFrames != value)
	{
		m_nNumFrames = value;
		emit dataChanged();
	}
}

int VisualObject::numFrames() const
{
	return m_nNumFrames;
}

void VisualObject::setAnimationSpeed( float speed )
{
	// use fuzzy compare
	if(!qFuzzyIsNull(m_fSpeed - speed))
	{
		m_fSpeed = speed;
		emit dataChanged();
	}
}

float VisualObject::animationSpeed() const
{
	return m_fSpeed;
}

void VisualObject::setLoop( bool bLoop )
{
	if(m_bLoop != bLoop)
	{
		m_bLoop = bLoop;
		emit dataChanged();
	}
}

bool VisualObject::isLoop() const
{
	return m_bLoop;
}

void VisualObject::setImageData( const ImageData& imageData )
{
	if(m_imageData != imageData)
	{
		m_imageData = imageData;
		emit dataChanged();
	}
}

const ImageData& VisualObject::imageData() const
{
	return m_imageData;
}

void VisualObject::generateAnimation()
{
	if(!m_nHorizontalPattern || !m_nNumFrames || m_imageData.image().isNull())
	{
		return;
	}

	m_frames.clear();

	if(m_nNumFrames < 2)
	{
		// not an animaton
		emit dataChanged();
		return;
	}

	int frameWidth = m_imageData.image().width()/m_nHorizontalPattern;
	// TODO: check this!
	int corrector = 0;

	if(m_nNumFrames%m_nHorizontalPattern != 0)
	{
		corrector = 1;
	}
	int frameHeight = m_imageData.image().height()/(m_nNumFrames/m_nHorizontalPattern + corrector);

	for(int i=0;i<m_nNumFrames;++i)
	{
		int hor = i%m_nHorizontalPattern;
		int ver = i/m_nHorizontalPattern;

		m_frames.append(QRect(hor*frameWidth, ver*frameHeight, frameWidth, frameHeight));
	}

	emit dataChanged();
}

const VisualObject::Frames& VisualObject::frames() const
{
	return m_frames;
}
